package cn.xingzhe.monster.user.domain.service;

import cn.xingzhe.monster.user.domain.model.PermissionModel;
import cn.xingzhe.monster.user.domain.model.RoleModel;
import cn.xingzhe.monster.user.domain.model.UserModel;
import cn.xingzhe.monster.user.domain.repository.PermissionRepository;
import cn.xingzhe.monster.user.domain.repository.RoleRepository;
import cn.xingzhe.monster.user.domain.repository.UserRepository;
import cn.xingzhe.monster.user.domain.exception.UserNotFoundException;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 权限领域服务
 * 处理权限查询相关的领域业务逻辑
 *
 * @author System
 * @version 1.0.0
 * @since 2024-01-01
 */
public class PermissionDomainService {

    private final UserRepository userRepository;
    private final RoleRepository roleRepository;
    private final PermissionRepository permissionRepository;

    public PermissionDomainService(UserRepository userRepository,
                                   RoleRepository roleRepository,
                                   PermissionRepository permissionRepository) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.permissionRepository = permissionRepository;
    }

    /**
     * 获取用户所有权限代码
     *
     * @param userId 用户ID
     * @return 权限代码列表
     */
    public List<String> getUserPermissionCodes(String userId) {
        UserModel user = userRepository.findById(userId)
                .orElseThrow(() -> UserNotFoundException.byId(userId));

        if (user.getRoleIds() == null || user.getRoleIds().isEmpty()) {
            return new ArrayList<>();
        }

        // 查询用户的所有角色
        List<RoleModel> roles = roleRepository.findByIds(user.getRoleIds());

        // 收集所有权限ID（去重）
        Set<String> permissionIds = new HashSet<>();
        for (RoleModel role : roles) {
            if (role.getPermissionIds() != null) {
                permissionIds.addAll(role.getPermissionIds());
            }
        }

        if (permissionIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 查询所有权限
        List<PermissionModel> permissions = permissionRepository.findByIds(new ArrayList<>(permissionIds));

        // 返回权限代码列表
        return permissions.stream()
                .map(PermissionModel::getPermissionCode)
                .collect(Collectors.toList());
    }

    /**
     * 检查用户是否有指定权限
     *
     * @param userId         用户ID
     * @param permissionCode 权限代码
     * @return 是否有权限
     */
    public boolean hasPermission(String userId, String permissionCode) {
        List<String> permissions = getUserPermissionCodes(userId);
        return permissions.contains(permissionCode);
    }
}

